package standino.velocity.db.db2.template;

import java.io.FileWriter;


import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.loader.FileResourceLoader;

public class Generator {
	final String packagePath = this.getClass().getPackage().getName().replace('.', '/');
	String desPath;

	String templatePath;

	private VelocityEngine velocityEngine;

	public Generator(String desPath, String templatePath) {
		super();
		this.desPath = desPath;
		this.templatePath = templatePath;
	}

	public void gen(String name, Object value) {

		try {
//			Properties p = new Properties();
//			p.setProperty("file.resource.loader.path", ".");
//			Velocity.init( p );
//			//Velocity.init();
			VelocityContext context = new VelocityContext();
			//context.put("name", new String("Velocity"));
			context.put(name,value);
//			Template template = null;
//
//			template = Velocity.getTemplate(templatePath);

			ExtendedProperties engineProperties = new ExtendedProperties();

	        // Tell VelocityTemplateEngine it should also use the
	        // classpath when searching for templates
	        // IMPORTANT: file,andromda.plugins the ordering of these
	        // two things matters, the ordering allows files to override
	        // the resources found on the classpath.
	        engineProperties.setProperty(VelocityEngine.RESOURCE_LOADER, "file,classpath");

	        engineProperties.setProperty(
	            "file." + VelocityEngine.RESOURCE_LOADER + ".class",
	            FileResourceLoader.class.getName());

	        engineProperties.setProperty(
	            "classpath." + VelocityEngine.RESOURCE_LOADER + ".class",
	            ClasspathResourceLoader.class.getName());
	        this.velocityEngine = new VelocityEngine();
	        this.velocityEngine.setExtendedProperties(engineProperties);
	        velocityEngine.init();
	        Template template = this.velocityEngine.getTemplate(packagePath+"/"+templatePath);
            //Template template = this.velocityEngine.getTemplate(templatePath);

			FileWriter fw = new FileWriter(this.desPath);
			//StringWriter sw = new StringWriter();
			template.merge( context, fw );
            fw.flush();
            fw.close();
		} catch (ResourceNotFoundException rnfe) {
			rnfe.printStackTrace();
			System.out.println("couldn't find the template");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
